import Vue from "vue";
import Vuex from "vuex";
// import axios from 'axios'
import appApi from '../../utils/api'

// import router from '../router'
Vue.use(Vuex);
export default {
    namespaced: true,
    state: {
        books: {
            loading_over: false,
            Namedparent: {
                key: '0',
                name: 'Unified'
            },
            detailquery: {
                searchtitle: '',
                id: ''
            },
            showdetail: false,
            bookinfo_already_show: false,
            show_sider: false,
            show_pagination: false,
            fieldsAllow: {
                sortFields: [
                    { id: "relevance", name: "相关度排序" },
                    { id: "title", name: "书名" },
                    { id: "author", name: "作者" },
                    { id: "publisher", name: "出版社" },
                    { id: "pubYear", name: "出版日期" },
                    { id: "callNo", name: "索书号" },
                ],
                searchAdvCode: { title: "", author: "03", publisher: "09", isbn: "05" },
                searchKeys: [
                    { "id": "", name: "任意词" },
                    { "id": "02", name: "书名" },
                    { "id": "03", name: "责任者" },
                    { "id": "04", name: "主题词" },
                    { "id": "05", name: "ISBN" },
                    { "id": "09", name: "出版社" },
                    { "id": "10", name: "丛书名" },
                    { "id": "07", name: "分类号" },
                    { "id": "08", name: "索书号" },
                ],
                sortTypes: ["desc", "asc"],
                pageSizeOptions: ['10', '20', '50', '100'],
                defaultPageSize: 20,
            },
            // qs: 请求参数
            qs: {
                q: '',
                p: 1, //这个是第几页
                site: '', //数据库id
            },
            // rs:检索结果
            rs: {
                total: 180,
                content: [
                    // {
                    //     "author": "(美) 鲁道夫·焦梅蒂著",
                    //     "callNo": "TP316.85/58",
                    //     "docTypeName": "中文图书",
                    //     "isbn": "978-7-111-59829-9",
                    //     "marcRecNo": "39697054624f516a5a3347416b53596b5a4e677741673d3d",
                    //     "num": 1,
                    //     "pubYear": "2018",
                    //     "publisher": "机械工业出版社",
                    //     "title": "GNU/Linux嵌入式快速编程"
                    // },
                    // {
                    //     "author": "杨明华, 谭励, 于重重等编著",
                    //     "callNo": "TP368.5/42",
                    //     "docTypeName": "中文图书",
                    //     "isbn": "978-7-121-06844-7, 978-7-89485-838-2",
                    //     "marcRecNo": "6d372b4458656d77675833676542487a5848492f50513d3d",
                    //     "num": 2,
                    //     "pubYear": "2008",
                    //     "publisher": "电子工业出版社",
                    //     "title": "LAMP网站开发黄金组合Linux+Apache+MySQL+PHP"
                    // },
                ],
                facetsList: [{
                        "facetList": [{
                                "code": "CHI",
                                "count": 13,
                                "name": "中文"
                            },
                            {
                                "code": "ENG",
                                "count": 1,
                                "name": "英语"
                            }
                        ],
                        "id": "langFacet",
                        "label": "语言"
                    },
                    {
                        "facetList": [{
                                "code": "2020",
                                "count": 1,
                                "name": "2020"
                            },
                            {
                                "code": "2018",
                                "count": 1,
                                "name": "2018"
                            },
                        ],
                        "id": "pubYearFacet",
                        "label": "出版年份"
                    }
                ],

                filters: [],
                "limiter": [],
                "sortField": "relevance",
                "sortType": "desc",
                pageSize: 20,
                "pageCount": 1,
                "locale": "zh_CN",
                "first": true,
            },

        },
    },
    mutations: {
        // 是否展示详情
        SHOW_DETAIL(state, status) {
            state.books.showdetail = status;
        },
        // 获取详情参数
        ChangeDetailQuery(state, status) {
            state.books.detailquery.searchtitle = status.searchtitle;
            state.books.detailquery.id = status.id;
        },
        // 是否展示侧边栏
        BOOKINFO_ALREADY_SHOW(state, is_show) {
            state.books.bookinfo_already_show = is_show;
        },
        // 清空搜索参数
        CLEAR_QS(state) {
            var qs = {
                searchWords: [{
                    fieldList: [
                        { fieldCode: "", fieldValue: "" },
                        // { "fieldCode": "", "fieldValue": "红楼梦", "fieldConj": "AND" },
                        // { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                    ],
                }],
                filters: [
                    // { fieldName: "subjectFacet", values: ["红楼梦", "文学研究"] },
                    // { fieldName: "locationFacet", values: ["03005"] },
                ],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 20,
                pageCount: 1, //这个是第几页
                locale: "zh_CN",
                first: true
            };
            state.books.qs = qs;
            state.books.rs.filters = [];
        },

        // UpdateQsFacets(state, facetsList) {
        //     state.books.qs.filters = [{ "fieldName": facetsList.id, "values": [facetsList.config_name] }];
        // },
        // 获取过滤条件
        UpdateRsfilters(state, facetsList) {
            state.books.rs.filters = facetsList;

            // state.books.rs.facetLists = facetLists;
        },
        // 获取返回的过滤条件
        UpdateRsFacets(state, facetsList) {
            state.books.rs.facetsList = facetsList;
        },
        // 获取总数
        UpdateRsTotal(state, total) {
            state.books.rs.total = total;
        },
        // 获取书籍列表
        UpdateRsContent(state, books) {
            state.books.rs.content = books;
        },
        // 统一检索 site
        Updateqssite(state, site) {
            console.log(site)
            state.books.qs.site = site;
        },
        ///
        /**
         * 更新qs 中的检索词
         * 1、更新keyword
         * 2、这里通通重置为第1页
         * 3、
         * searchWords: [
                    {
                        fieldList: [
                            { fieldCode: "", fieldValue: "红楼梦" },
                            { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                        ],
                    }
                ],
         * @param {*} state 
         * @param {检索词，是} search_keyword 
         * 
         */
        UpdateQsSearchKeyWord(state, search_keyword, current_page) {
            this.commit(state.books.Namedparent.name + "/UpdateQsSearchKeyWordV2", search_keyword, current_page);
        },
        UpdateQsSearchKeyWordV2(state, search_keyword) {
            state.books.qs.q = search_keyword;
            state.books.qs.p = 1;
        },
        //高级检索条件，多个关键词
        UpdateQsSearchFieldListAdv(state, search_field_list) {
            state.books.qs.searchWords[0].fieldList = search_field_list;
        },
        // 年代限制 ["DT:1999/2021"] 这种格式
        UpdateQsLimiter(state, limiter) {
            state.books.qs.limiter = limiter;
        },
        ChangeQsSearchField(state, search_field) {
            state.books.qs.searchWords[0].fieldList[0].fieldCode = search_field;
        },

        // },
        // 获取搜索类型
        ChangeSortType(state, sortType) {
            state.books.qs.sortType = sortType;
        },
        // 获取排序
        ChangeSortField(state, sortField) {
            state.books.qs.sortField = sortField;
            // state.books.qs. = sortField;
        },
        // 获取页码
        ChangeCurrentPage(state, currentPage) {
            state.books.qs.p = currentPage;
        },
        // 获取页码
        ChangeCurrentPageWithOutSync(state, currentPage) {
            state.books.qs.p = currentPage;
        },
        // 获取每页数量
        ChangePageSize(state, pageSize) {
            state.books.qs.pageSize = pageSize;
            state.books.rs.pageSize = pageSize;
            state.books.fieldsAllow.pageSize = pageSize;
            var current_page = state.books.qs.pageCount;
            var total = state.books.rs.total;
            if (current_page * pageSize > total) {
                current_page = Math.ceil(total / pageSize);
                this.commit("ChangeCurrentPage", current_page);
            }
        },
        // 清空书籍列表
        ClearBooksContents(state) {
            state.books.rs.content = [];
        },
        PARAMS_INIT_QS(state, rs) {
            state.books.rs = rs;

        },
        // 是否展示侧标栏
        SHOW_SIDER(state, status) {
            state.books.show_sider = status;
        },
        // 是否展示分页
        SHOW_PAGINATION(state, status) {
            state.books.show_pagination = status;
        },

        AddBook(state, {
            author,
            category,
            bisbn,
            isbn,
            pub_year,
            publisher,
            title,
            filetype,
            bookid,
            cover
        }) {
            var book = {
                author: author,
                category: category,
                bisbn: bisbn,
                isbn: isbn,
                pub_year: pub_year,
                publisher: publisher,
                title: title,
                filetype: filetype,
                bookid: bookid,
                cover: cover,
            };
            state.books.rs.content.push(book);
        },
        removeFilters(state, index) {
            // 移除弹窗
            state.dialogList.splice(index, 1);
        },
        SearchSideUpdateFilters(state, fieldName) {
            //数据结构 { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },
            console.log(fieldName)
            this.commit('Unified/Updateqssite', fieldName);
            this.dispatch("Unified/GetBooks")

        },
        Changeloading(state, status) {
            state.books.loading_over = status;
        }
    },
    actions: {
        // 初始化加载数据
        GetBooks(context) {
            if (context.state.books.qs.site == '') {
                context.state.books.qs.site = context.state.books.qs.filters[0].fieldName
            }
            appApi.unifiedgetbook(context.state.books.qs)
                .then(response => {
                    if (response.status == 200) {
                        if (context.state.books.rs.content.length > 0) {
                            context.state.books.rs.content = [];
                        }
                        var book_length = [];
                        for (let i in response.data.result.All_results) {
                            book_length.push(
                                response.data.result.All_results[i]
                            )
                        }
                        for (let i = 0; i < book_length.length; i++) {
                            var book = {
                                content: '',
                                db: '',
                                title: '',
                                url: '',
                                num: ''
                            };

                            book.title = book_length[i].title,
                                book.content = book_length[i].content,
                                book.db = book_length[i].db,
                                book.url = book_length[i].url,
                                book.num = ''
                            context.state.books.rs.content.push(book)
                        }


                        context.commit("SHOW_PAGINATION", true);
                        context.commit("SHOW_SIDER", true);
                        // context.state.books.rs.content = books;
                        context.commit("UpdateRsContent", context.state.books.rs.content); //统一检索结果
                        context.commit("UpdateRsTotal", parseInt(response.data.result.Total ? response.data.result.Total : '1'));
                        context.state.books.rs.pageSize = response.data.result.Count;
                        context.state.books.loading_over = false;
                    }
                }).catch(err => {
                    console.log(err);
                });


        },
        // 获取侧边栏
        getsiderbar(context) {
            var ids = 0;
            appApi.findsite('')
                .then(response => {
                    if (response.status == 200) {
                        var datas = response.data.result;
                        var nList = [];
                        // 对slider归类
                        for (var i = 0; i < datas.length; i++) {
                            (i => {

                                setTimeout(() => {
                                    context.state.books.qs.site = datas[i].id
                                    appApi.unifiedgetbook(context.state.books.qs)
                                        .then(response => {
                                            if (response.status == 200) {
                                                if (response.data.result.Total > 0) {
                                                    if (ids == 0) {
                                                        context.commit("Updateqssite", datas[i].id);
                                                        //context.commit("UpdateQsFacets", datas[i]);
                                                        ids = datas[i].id
                                                    }
                                                    datas[i].count = response.data.result.Total;
                                                    if (nList.length == 0) {
                                                        nList.push({
                                                            label: datas[i].classname,
                                                            facetList: [datas[i]]
                                                        })
                                                    } else {
                                                        var index = nList.findIndex(item => item.label == datas[i].classname);
                                                        if (index >= 0) {
                                                            nList[index].facetList.push(datas[i])
                                                        } else {
                                                            nList.push({
                                                                label: datas[i].classname,
                                                                facetList: [datas[i]]
                                                            })
                                                        }
                                                    }
                                                }
                                            }
                                        }).catch(err => {
                                            console.log(err);
                                        });
                                }, 3)
                            })(i)

                        }
                        context.commit("UpdateRsfilters", response.data.result[0]);
                        // context.commit("UpdateQsFacets", nList[0].facetList[0].id);
                        context.commit("UpdateRsFacets", nList);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
    },
    getters: {
        // getQS: state => {
        //     return state.books.qs;
        //     // return state.books.filter(todo => todo.done)
        // }
    }
}